package org.graffitidiary.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.okhttplib.HttpInfo;
import com.okhttplib.OkHttpUtil;
import com.okhttplib.callback.CallbackOk;
import com.okhttplib.callback.ProgressCallback;

import org.graffitidiary.R;
import org.graffitidiary.adapter.ItemFriendsAdapter;
import org.graffitidiary.adapter.ItemToDrawAdapter;
import org.graffitidiary.bean.FileInfo;
import org.graffitidiary.bean.FriendList.Informationlist;
import org.graffitidiary.bean.FriendList.JsonRootBean;
import org.graffitidiary.framework.ui.ActionBarActivity;
import org.graffitidiary.manager.Dbs;
import org.graffitidiary.utils.GloableParams;
import org.graffitidiary.utils.ToastUtil;
import org.graffitidiary.view.refresh.RefreshLayout;
import org.graffitidiary.view.refresh.RefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.okhttplib.annotation.CacheLevel.FIRST_LEVEL;

/**
 * Created by 70339 on 2016/11/30.
 */

public class ToDrawActivity extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener, RefreshLayout.OnLoadListener{
    private String s_uid = "";
    RefreshLayout refresh;
    RefreshListView listview;
    Button btn_to_draw;
    Button btn_send;

    List<Informationlist> list = new ArrayList<Informationlist>();
    ItemToDrawAdapter itemToDrawAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showBar();
        setBarTitle("对画列表");

    }

    @Override
    protected int setLayout() {
        return R.layout.activity_to_draw;
    }

    @Override
    protected void initViews() {
        btn_to_draw = (Button) findViewById(R.id.btn_to_draw);
        btn_to_draw.setOnClickListener(this);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);

        refresh = (RefreshLayout) findViewById(R.id.refresh);
        refresh.setOnRefreshListener(this);
        listview = (RefreshListView) findViewById(R.id.listview);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String filePath = list.get(position).getDiarypath();
                Intent intent = new Intent(ToDrawActivity.this, AutoDrawActivity.class);
                intent.putExtra("Name", list.get(position).getGraffitiname());
                intent.putExtra("fileName", "bsnd");
                intent.putExtra("filePath", filePath);
                startActivity(intent);
            }
        });

        Intent intent = getIntent();
        s_uid = intent.getStringExtra("s_uid");
        showProgressDialog();
        getDrawList(GloableParams.token, s_uid, "");
    }

    int getDrawListSize;
    private void getDrawList(String token, String a_uid, String e_id) {
        OkHttpUtil okHttpUtil = OkHttpUtil.Builder()
                .setCacheLevel(FIRST_LEVEL)
                .setConnectTimeout(25).build(this);
        okHttpUtil.doPostAsync(
                HttpInfo.Builder().setUrl(GloableParams.PROXY_IP + "InformationList.php")
                        .addParam("token", token)
                        .addParam("s_uid", s_uid)
                        .addParam("e_id", e_id)
                        .build(),
                new CallbackOk() {
                    @Override
                    public void onResponse(HttpInfo info) throws IOException {
                        closeProgressDialog();
                        if (info.isSuccessful()) {
                            String result = info.getRetDetail();
                            try {
                                JSONObject object = new JSONObject(result);
                                if("200".equals(object.getString("code"))){
                                    JsonRootBean json = JSON.parseObject(result, JsonRootBean.class);
                                    List<Informationlist> list2 = new ArrayList<Informationlist>();
                                    list2 = json.getInformationlist();
                                    getDrawListSize = list2.size();
                                    Collections.reverse(list2);
                                    list.addAll(0, list2);
                                    display();
                                }else{
                                    if(refresh.isRefreshing()){
                                        refresh.setRefreshing(false);
                                        ToastUtil.showShortToast("没有更多了");
                                    }else{
                                        listview.setSelection(list.size());
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShortToast(info.getRetDetail());
                        }
                    }
                });
    }

    boolean isAdapter = true;
    private void display() {
        if(isAdapter){
            itemToDrawAdapter = new ItemToDrawAdapter(list);
            itemToDrawAdapter.notifyDataSetChanged();
            listview.setAdapter(itemToDrawAdapter);
            listview.setVisibility(View.VISIBLE);
            isAdapter = false;
        }else{
            itemToDrawAdapter.notifyDataSetChanged();
            listview.setAdapter(itemToDrawAdapter);
        }
        itemToDrawAdapter.notifyDataSetChanged();

        if(refresh.isRefreshing()){
            refresh.setRefreshing(false);
            listview.setSelection(getDrawListSize);
        }else{
            listview.setSelection(list.size());
        }

    }

    private void display2() {
        if(fileInfo2 != null){
            updateFileInfo(fileInfo2.getId() + "");
            Informationlist informationlist = new Informationlist();
            informationlist.setDiarypath(fileInfo2.getFileName());
            informationlist.setGraffitiname(fileInfo2.getFileNick());
            informationlist.setExchangetime(new Date());
            informationlist.setAUid(Integer.parseInt(s_uid));
            informationlist.setSUid(GloableParams.id);
            list.add(informationlist);
            fileInfo2 = null;
        }
        display();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_to_draw:
                Intent intent = new Intent(ToDrawActivity.this, MainActivity.class);
                intent.putExtra("toDraw", "toDraw");
                startActivityForResult(intent, 10086);
                break;
            case R.id.btn_send:

                if(fileInfo2 != null){
                    showProgressDialog();
                    send(fileInfo2);
                }else{
                    ToastUtil.showLongToast("请先画点东西");
                }

                break;
        }
    }

    private void send(FileInfo fileInfo) {
        uploadFile(fileInfo.getFilePath(), fileInfo.getFileNick());
    }


    /**
     * 上传文件
     * @param path 本地文件地址
     * @param GraffitiName 文件名
     */
    private void uploadFile(String path, String GraffitiName) {
        if(TextUtils.isEmpty(path)){
            return;
        }

        HttpInfo info = HttpInfo.Builder()
                .setUrl(GloableParams.PROXY_IP + "SendMessage.php")
                .addParam("token", GloableParams.token)
                .addParam("s_uid", s_uid)
                .addParam("graffitiname", GraffitiName)
                .addUploadFile("uploadedfile",path,new ProgressCallback(){
                    @Override
                    public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
                        System.out.println("上传进度：" + percent);
                    }

                    @Override
                    public void onResponseSync(String filePath, HttpInfo info) {
                        super.onResponseSync(filePath, info);
                        if (info.isSuccessful()) {
                            try {
                                JSONObject json = new JSONObject(info.getRetDetail());
                                String s = json.getString("code");
                                if("200".equals(s)){
                                    closeProgressDialog();
                                    display2();
                                }else{
                                    ToastUtil.showLongToast("发送失败");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShortToast(info.getRetDetail());
                        }
                    }

                })
                .build();
        OkHttpUtil.getDefault(this).doUploadFileAsync(info);
    }

    /**
     * 修改用户本地文件上传后的数据状态
     */
    private void updateFileInfo(String id) {
        try {
            Dbs.getDb(this);
            FileInfo fileInfo = Dbs.getDb().findById(FileInfo.class, id);
            if(fileInfo != null){
                fileInfo.setFileState(1);
                Dbs.getDb().update(fileInfo);
            }
            Dbs.close();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    FileInfo fileInfo2;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case 10086:
                FileInfo fileInfo = (FileInfo) data.getExtras().get("fileInfo");
                try {
                    fileInfo2 = Dbs.getDb().findFirst(Selector.from(FileInfo.class).where("filePath", "=", fileInfo.getFilePath()));
                    btn_to_draw.setText(fileInfo2.getFileNick());
                } catch (DbException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void onRefresh() {
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                getDrawList(GloableParams.token, s_uid, list.get(0).getEId() + "");
            }
        }, 0);
    }

    @Override
    public void onLoad() {

    }
}
